package com.bjfu.face.utils;

import com.baidu.aip.face.AipFace;
import com.bjfu.servicebase.exceptionHandler.CommonException;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;

@Component
public class BaiduUtils {
    @Value("${baidu.app-id}")
    private String APP_ID;

    @Value("${baidu.api-key}")
    private String API_KEY;

    @Value("${baidu.secret-key}")
    private String SECRECT_KEY;

    @Value("${baidu.image-type}")
    private String IMAGE_TYPE;

    @Value("${baidu.group-id}")
    private String GROUP_ID;

    private AipFace client;

    private HashMap<String, String> options = new HashMap<String, String>();

    public BaiduUtils(){
        options.put("quality_control","NORMAL");
        options.put("liveness_control","NONE");
    }

    @PostConstruct
    public void init(){
        client = new AipFace(APP_ID,API_KEY,SECRECT_KEY);
    }

    public JSONArray faceDetect(String image){
        options.put("face_field","age,beauty,glasses,emotion,face_shape,gender");
        options.put("max_face_num", "10");
        options.put("face_type", "LIVE");
        JSONObject res = client.detect(image, IMAGE_TYPE, options);
        if(res.has("error_code") && res.getInt("error_code")!=0){

            throw new CommonException(20001,"图片中不含人脸面部信息");
        }
        JSONArray faceList = res.getJSONObject("result").getJSONArray("face_list");
        return faceList;
    }


}
